<?php
/**
 * Action.php
 *
 * @category    Madoqua
 * @package     View
 * @subpackage  Helper
 */

/** base class */
require_once 'Zend/View/Helper/Action.php';

/** Madoqua's wicked cool action cache */
require_once 'Madoqua/Cache/Action.php';

/**
 * Madoqua_View_Helper_Action
 *
 * view helper with caching enabled, well, if the config says it's ok :x
 *
 * @category    Madoqua
 * @package     View
 * @subpackage  Helper
 */
class Madoqua_View_Helper_Action extends Zend_View_Helper_Action
{
    /**
     * the cache
     *
     * @var Zend_Cache_Core
     */
    protected $_cache;

    /**
     * the view object
     *
     * @var Zend_View
     */
    protected $_view;

    /**
     * constructor
     */
    public function __construct() {
        parent::__construct();

        $this->_cache = Madoqua_Cache_Action::get();
        //the action cache
    }

    /**
     * set the view
     *
     * @param Zend_View $view
     */
    public function setView(Zend_View_Interface $view)
    {
        $this->_view = $view;
    }

    /**
     * overloaded action :)
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module Defaults to default module
     * @param  array $params
     * @param  bool $noCache bypass cache, do *NOT* save a cached result
     * @return string
     * @todo have a look at the placeholder helper
     */
    public function Action($action, $controller, $module = null, array $params = array(), $noCache = false)
    {
        if (!$noCache) {
            //user requested caching, but maybe the config doesn't allow it...
            $config = Madoqua_Application::getConfiguration();
            $noCache = !(bool) $config->caching->enable;
        }
        //see if the config allows for caching

        if ($noCache) {
            return parent::action($action, $controller, $module, $params);
        }
        //bypass caching alltogether (also won't save to cache (!!!))

        if ($module == null) {
            $module = Madoqua_Application::getFront()->getRequest()->getModuleName();
        }
        //make module default to current

        $tags = Madoqua_Cache_Action::getTags($module, $controller, $action);
        $id = Madoqua_Cache_Action::getId($module, $controller, $action);
        //get the id and tags... hmm... could be prettier.

        if (!$result = $this->_cache->load($id)) {
            //no hit in cache
            $result = parent::action($action, $controller, $module, $params);
            //dispatch the action
            $this->_cache->save($result, $id, $tags);
            //save for later use
        }
        return $result;
    }
}